package models

import (
	"fmt"

	"github.com/beego/beego/v2/client/orm"
)

// MemberLevel 会员等级模型
type MemberLevel struct {
	BaseModel
	Name        string  `orm:"size(50)" json:"name"`
	Icon        string  `orm:"size(255)" json:"icon"`
	Code        string  `orm:"size(50)" json:"code"` // 会员等级编码，用于在程序中识别会员等级，如VIP、SVIP等
	Description string  `orm:"size(255)" json:"description"`
	Discount    float64 `orm:"digits(10);decimals(2)" json:"discount"`   // 折扣率，如0.95表示95折
	PointsLimit int     `orm:"default(0)" json:"points_limit"`           // 所需积分
	PointRate   float64 `orm:"digits(10);decimals(2)" json:"point_rate"` // 积分兑换率，如100积分兑换1元
	Status      int8    `orm:"default(1)" json:"status"`                 // 1:正常, 0:禁用
	SortOrder   int     `orm:"default(0)" json:"sort_order"`             // 排序
	Benefits    string  `orm:"size(500)" json:"benefits"`                // 会员权益，JSON格式存储
}

// TableName 设置表名
func (m *MemberLevel) TableName() string {
	return "ss_member_level"
}

// GetMemberLevelById 根据ID获取会员等级信息
func GetMemberLevelById(id int64, franchiseId int64) (*MemberLevel, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberLevel)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	level := &MemberLevel{}
	err := qs.One(level)
	return level, err
}

// GetMemberLevelList 获取会员等级列表
func GetMemberLevelList(page, pageSize int, filters map[string]interface{}) ([]*MemberLevel, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberLevel))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 加盟商过滤
	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var levels []*MemberLevel
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&levels)

	return levels, total, err
}

// CreateMemberLevel 创建会员等级
func CreateMemberLevel(level *MemberLevel) (int64, error) {
	o := orm.NewOrm()

	// 验证加盟商ID
	if level.FranchiseId <= 0 {
		return 0, fmt.Errorf("加盟商ID不能为空")
	}

	id, err := o.Insert(level)
	return id, err
}

// UpdateMemberLevel 更新会员等级信息
func UpdateMemberLevel(level *MemberLevel, franchiseId int64, fields ...string) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberLevel)).Filter("id", level.Id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	existingLevel := &MemberLevel{}
	err := qs.One(existingLevel)
	if err != nil {
		return err
	}

	// 确保不修改加盟商ID
	level.FranchiseId = existingLevel.FranchiseId
	_, err = o.Update(level, fields...)
	return err
}

// DeleteMemberLevel 删除会员等级（软删除）
func DeleteMemberLevel(id int64, franchiseId int64) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberLevel)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	level := &MemberLevel{}
	err := qs.One(level)
	if err != nil {
		return err
	}

	level.IsDeleted = 1
	_, err = o.Update(level, "IsDeleted")
	return err
}

// GetAllActiveMemberLevels 获取所有激活的会员等级
func GetAllActiveMemberLevels(franchiseId int64) ([]*MemberLevel, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberLevel)).Filter("status", 1).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	var levels []*MemberLevel
	_, err := qs.OrderBy("sort_order").All(&levels)
	return levels, err
}
